//
//  YZBaseTopVC.m
//  VET
//
//  Created by lixiaoyi on 2018/7/19.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZBaseTopVC.h"

#import "YZMessageListModel.h"
#import "ClientSocket.h"
#import "YZChatUtils.h"
#import "varint.h"
#import "YZMessageFrame.h"
#import "YZMessageConst.h"
#import "YZMessageHelper.h"
#import "UIImage+YZExtension.h"
#import "NSString+YZExtension.h"
#import "YZMediaManager.h"
#import "YZImageManager.h"
#import "YZDBManager.h"
#import "YZSystemMessageVC.h"
#import "YZUser.h"
#import "YZFriendModel.h"
#import "YZMessageConst.h"
#import "UIView+YZBadge.h"
#import "YZChatPeer.h"
#import "YZNetworkConfig.h"

@interface YZBaseTopVC ()<ClientSocketDelegate>
@property (nonatomic, strong) NSFileManager *fileMgr;
@property (nonatomic, copy) NSString *audioRecoderSavePath;
@property (nonatomic, copy) NSString *tempRecorderPath;
@property (nonatomic, copy) NSString *recorderName;
// 所有接收到的数据大小
@property (nonatomic) NSUInteger allSize;

// 所有接收到的数据
@property (nonatomic, strong) NSMutableData *allData;

// 待读字节
@property (nonatomic) unsigned long long bufferSize;

// 缓冲区
@property (nonatomic, strong) NSMutableData *buffer;

// 发送的消息
@property (nonatomic, strong) ImMessage *mess;

// 是否有新朋友申请
@property (nonatomic) BOOL haveLatestFriend;

/**
 最新的好友申请
 */
@property (nonatomic, strong) YZFriendModel *lastestModel;

/**
 最新的好友申请数组
 */
@property (nonatomic, strong) NSMutableArray *lastestModelArr;
@end

@implementation YZBaseTopVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 待读字节数
    _bufferSize = 0;
    
    // 缓冲区
    _buffer = [NSMutableData data];
    
    // 设置是否有最新申请
    _haveLatestFriend = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [ClientSocket shareSocket].socketHost = [YZNetworkConfig getImDomain][@"ip"];
    [ClientSocket shareSocket].socketPort = [[YZNetworkConfig getImDomain][@"port"] integerValue];
    [[ClientSocket shareSocket] autoConnection];
    [ClientSocket shareSocket].socketDelegate = self;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [ClientSocket shareSocket].socketDelegate = nil;
    [[ClientSocket shareSocket] disConn];
    [ClientSocket attempDealloc];
}

#pragma mark - APP进入前台的事件
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                    selector:@selector(applicationWillEnterForeground:)
                                        name:UIApplicationWillEnterForegroundNotification
                                               object:app];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)applicationWillEnterForeground:(NSNotification *)notification{
    [ClientSocket shareSocket].socketHost = [YZNetworkConfig getImDomain][@"ip"];
    [ClientSocket shareSocket].socketPort = [[YZNetworkConfig getImDomain][@"port"] integerValue];
    [[ClientSocket shareSocket] autoConnection];
    [ClientSocket shareSocket].socketDelegate = self;
}


- (NSString *)audioRecoderSavePath {
    if (!_audioRecoderSavePath) {
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString *dateFolder = [formatter stringFromDate:date];
        NSString *dateAudioPath = [NSString stringWithFormat:@"%@/",dateFolder];
        // 文件目录
//        NSLog(@"homeDic--->%@",NSHomeDirectory());
//        NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//        _audioRecoderSavePath = [NSString stringWithFormat:@"%@/%@",documentDirectory,dateAudioPath];
        
        NSString *cacheAudioPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        _audioRecoderSavePath = [NSString stringWithFormat:@"%@/%@",cacheAudioPath,dateAudioPath];
    }
    
    return _audioRecoderSavePath;
}


#pragma mark - ClientSocketDelegate
- (void)clientSocket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"建立连接成功");
    [[ClientSocket shareSocket].socket readDataWithTimeout:-1 tag:101];
    [ClientSocket shareSocket].connectd = YES;
    // 开启定时器
    if ([ClientSocket shareSocket].connectTimer) {
        [[ClientSocket shareSocket].connectTimer invalidate];
        [ClientSocket shareSocket].connectTimer = nil;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[ClientSocket shareSocket] addTimer];
    });
}

- (void)clientSocket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    
    if (100 == tag) {
        // 心跳
    }
    else if (101 == tag) {
        // conn
        NSString *text = [YZChatUtils convertDataToHexStr:data];
        NSString *printText = [NSString stringWithFormat:@"服务器返回--->%@",text];
        NSLog(@"%@",printText);
        char *str = (char *)[data bytes];
        unsigned char bts;
        unsigned long long r = varint_decode(str, 7, &bts);
        
        int btsLen = (int)bts;
        // 反序列化
        NSMutableString *realStr = [NSMutableString string];
        if (r * 2 <= text.length - btsLen * 2) {
            NSString *tempStr = [text substringWithRange:NSMakeRange(btsLen * 2, r * 2)];
            realStr = [NSMutableString stringWithString:tempStr];
            
            NSData *realData = [YZChatUtils dataFormHexString:realStr];
            ImMessage *p = [ImMessage parseFromData:realData error:nil];
            //            DLog(@"p>>>%@",p);
            
            // 打印确认接收报文日志
            if ([p.messageType isEqualToString:@"ack"]) {
                NSLog(@"收到服务器确认");
            } else if ([p.messageType isEqualToString:@"data"]) {
                NSLog(@"确认接收消息，发送ack消息");
                // 显示离线消息
                NSString *recStr = [[NSString alloc] initWithData:p.payload encoding:NSUTF8StringEncoding];
                NSString *showMsg = [NSString stringWithFormat:@"收到离线消息--->%@",recStr];
                NSLog(@"%@",showMsg);
                
                // 给服务器发送ack,确认收到离线消息
                [[ClientSocket shareSocket] doAck:p.messageId];
            };
        }
    } else {
        _allSize += data.length;
        [_allData appendData:data];
        NSLog(@"_allsize--->%ld",_allSize);
        [self readBytes:data];
    }
    
    
    // 继续接收数据
    [[ClientSocket shareSocket].socket readDataWithTimeout:-1 tag:0];
}

- (void)readBytes:(NSData *)data {
    // 过滤心跳包
    NSString *text = [YZChatUtils convertDataToHexStr:data];
    if ([self isDelayHeartRecData:text]) {
        NSLog(@"接收心跳OK");
        [ClientSocket shareSocket].receHearDt = [NSDate date];
        NSTimeInterval interlTimer = [[ClientSocket shareSocket].receHearDt timeIntervalSinceDate:[ClientSocket shareSocket].sendHeartDt];
        if (interlTimer < HEART_TIME * 2) {
            interlTimer = 0;
            return;
        } else {
            // 连接失效，客户端关闭socket并重新建立连接
            NSLog(@"心跳失效，重新连接");
            
            // 重新连接
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ClientSocket shareSocket] autoConnection];
            });
        }
    }
    
    // 如果待读字节数大于0
    if (_bufferSize > 0) {
        if (data.length < _bufferSize) {
            // 继续读
            _bufferSize = _bufferSize - data.length;
            [_buffer appendData:data];
        } else {
            NSData *temp = [data subdataWithRange:NSMakeRange(0, _bufferSize)];
            [_buffer appendData:temp];
            // 解析数据
            ImMessage *p = [ImMessage parseFromData:_buffer error:nil];
            NSLog(@"p>>>%@",p);
            // 打印确认接收报文日志
            if ([p.messageType isEqualToString:@"ack"]) {
                NSLog(@"收到服务器确认");
            } else if ([p.messageType isEqualToString:@"data"]) {
                NSLog(@"确认接收消息，发送ack消息");
                // 显示离线消息
                NSString *recStr = [[NSString alloc] initWithData:p.payload encoding:NSUTF8StringEncoding];
                NSString *showMsg = [NSString stringWithFormat:@"收到离线消息--->%@",recStr];
                NSLog(@"%@",showMsg);
                // 刷新页面
                [self accpetMessage:p];
            } else if ([p.messageType isEqualToString:@"friend"]) {
                NSLog(@"收到好友申请消息");
                // 刷新页面
                [self accpetMessage:p];
            };
            
            // 剩余的再处理一次
            NSUInteger leftInt = data.length - _bufferSize;
            if (leftInt > 0) {
                NSData *leftData = [data subdataWithRange:NSMakeRange(_bufferSize, data.length - _bufferSize)];
                
                // 重置buffer
                _bufferSize = 0;
                _buffer = [NSMutableData data];
                
                [self readBytes:leftData];
            } else {
                // 重置buffer
                _bufferSize = 0;
                _buffer = [NSMutableData data];
            }
        }
    } else {
        char *str = (char *)[data bytes];
        unsigned char bts;
        unsigned long long r = varint_decode(str, 7, &bts);
        int btsLen = (int)bts;
        if (data.length < r + btsLen) {
            _bufferSize = r - data.length + btsLen;
            NSData *appData = [data subdataWithRange:NSMakeRange(btsLen, data.length - btsLen)];
            [_buffer appendData:appData];
        } else if (data.length == r + btsLen) {
            // 解析数据
            NSData *tempData = [data subdataWithRange:NSMakeRange(btsLen, r)];
            ImMessage *p = [ImMessage parseFromData:tempData error:nil];
            NSLog(@"p>>>%@",p);
            
            // 打印确认接收报文日志
            if ([p.messageType isEqualToString:@"ack"]) {
                NSLog(@"收到服务器确认");
            } else if ([p.messageType isEqualToString:@"data"]) {
                NSLog(@"确认接收消息，发送ack消息");
                // 显示离线消息
                NSString *recStr = [[NSString alloc] initWithData:p.payload encoding:NSUTF8StringEncoding];
                NSString *showMsg = [NSString stringWithFormat:@"收到离线消息--->%@",recStr];
                NSLog(@"%@",showMsg);
                
                // 刷新页面
                [self accpetMessage:p];
                
                
            } else if ([p.messageType isEqualToString:@"friend"]) {
                NSLog(@"收到好友申请消息");
                // 刷新页面
                [self accpetMessage:p];
            };
        } else if (data.length > r + btsLen) {
            // 粘包
            NSData *appData = [data subdataWithRange:NSMakeRange(r + btsLen + btsLen, data.length - r - btsLen - btsLen)];
            [_buffer appendData:appData];
            NSData *dealData = [data subdataWithRange:NSMakeRange(btsLen, r)];
            
            // 解析数据
            ImMessage *p = [ImMessage parseFromData:dealData error:nil];
            NSLog(@"p>>>%@",p);
            
            // 打印确认接收报文日志
            if ([p.messageType isEqualToString:@"ack"]) {
                NSLog(@"收到服务器确认");
            } else if ([p.messageType isEqualToString:@"data"]) {
                NSLog(@"确认接收消息，发送ack消息");
                // 显示离线消息
                NSString *recStr = [[NSString alloc] initWithData:p.payload encoding:NSUTF8StringEncoding];
                NSString *showMsg = [NSString stringWithFormat:@"收到离线消息--->%@",recStr];
                NSLog(@"%@",showMsg);
                // 刷新页面
                [self accpetMessage:p];
            } else if ([p.messageType isEqualToString:@"friend"]) {
                NSLog(@"收到好友申请消息");
                // 刷新页面
                [self accpetMessage:p];
            };
            
            // 剩余的再处理一次
            NSUInteger leftInt = data.length - btsLen - r;
            if (leftInt > 0) {
                NSData *leftData = [data subdataWithRange:NSMakeRange(btsLen + r, data.length - btsLen - r)];
                
                // 重置buffer
                _bufferSize = 0;
                _buffer = [NSMutableData data];
                
                [self readBytes:leftData];
            } else {
                // 重置buffer
                _bufferSize = 0;
                _buffer = [NSMutableData data];
            }
        }
    }
}

- (void)accpetMessage:(ImMessage *)p {
    // 刷新页面
    NSString *receiveType = @"";
    NSString *path = @"";
    __block NSString *fileKey = nil;
    
    
    if ([p.mediaType isEqualToString:@"text/plain"]) {
        
        receiveType = TypeText;
        YZMessageFrame *messageF = [YZMessageHelper createMessageFrame:receiveType imMessage:p path:path fileKey:nil isSender:NO rececivedSenderbySelf:NO senderAvatar:[YZChatPeer shared].receiverAvatar receiverAvatar:[YZUser sharedInstance].avatar];
        
        // 接收Model
        NSString *recStr = [[NSString alloc] initWithData:p.payload encoding:NSUTF8StringEncoding];
        YZMessageListModel *model = [YZMessageListModel new];
        model.name = p.sender;
        model.imageName = [YZChatPeer shared].receiverAvatar;
        model.showUserId = p.sender;
        model.message = recStr;
        model.time = p.messageTime;
        model.receiver = p.receiver;
        model.showRedHot = YES;
        
        // 从数据库查询红点数量，没有查到就是0
        model.redHotNumber = [self refreshRedHotNum:model];
        NSLog(@"redHotNumber---------->%@",model.redHotNumber);
        
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:RefreshMessaegListNotification object:model];
        
        // 更新【tab-消息】小红点
        [[NSNotificationCenter defaultCenter] postNotificationName:ShowTabRedDotNotification object:@(0)];
        
        // 给服务器发送ack,确认收到离线消息
        [[ClientSocket shareSocket] doAck:p.messageId];
        
        // 保存消息
        [self saveAcceptedMessage:messageF];
        
    }
    else if ([p.mediaType isEqualToString:@"audio/aac"]) {
        
        receiveType = TypeVoice;
        // 保存录音文件名
        [self saveReceviceAudio:p.payload];
        path = _tempRecorderPath;
        
        YZMessageFrame *messageF = [YZMessageHelper createMessageFrame:receiveType imMessage:p path:path fileKey:nil isSender:NO rececivedSenderbySelf:NO senderAvatar:[YZChatPeer shared].receiverAvatar receiverAvatar:[YZUser sharedInstance].avatar];
        
        // 接收Model
        NSString *recStr = @"[语音]";
        YZMessageListModel *model = [YZMessageListModel new];
        model.name = p.sender;
        model.imageName = @"";
        // showUserId这里指发送方
        model.showUserId = p.sender;
        model.message = recStr;
        model.time = p.messageTime;
        model.receiver = p.receiver;
        model.showRedHot = YES;
        
        // 从数据库查询红点数量，没有查到就是0
        model.redHotNumber = [self refreshRedHotNum:model];
        
        NSLog(@"redHotNumber---------->%@",model.redHotNumber);
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:RefreshMessaegListNotification object:model];
        
        // 给服务器发送ack,确认收到离线消息
        [[ClientSocket shareSocket] doAck:p.messageId];
        
        // 保存消息
        [self saveAcceptedMessage:messageF];
        
    } else if ([p.mediaType isEqualToString:@"image/*"]) {
        
        receiveType = TypePic;
        // 保存图片
        UIImage *thumbnailImage = [UIImage imageWithData:p.payload];
        
        UIImage *simpleImage = [UIImage simpleImage:thumbnailImage];
        
        path = [[YZMediaManager shareManager] saveImage:simpleImage];
        
        // 原图的Url
        NSString *orginImagUrlStr = p.mediaLink;
        
        [[YZImageManager shareManager] requestWithUrlStr:orginImagUrlStr
                                               mediaType:p.mediaType
                                                   block:^(NSString *str) {
                                                       fileKey = str;
                                                       YZMessageFrame *messageF = [YZMessageHelper createMessageFrame:receiveType imMessage:p path:fileKey fileKey:fileKey isSender:NO rececivedSenderbySelf:NO senderAvatar:[YZChatPeer shared].receiverAvatar receiverAvatar:[YZUser sharedInstance].avatar];
                                                       
                                                       // 接收Model
                                                       NSString *recStr = @"[图片]";
                                                       YZMessageListModel *model = [YZMessageListModel new];
                                                       model.name = p.sender;
                                                       model.imageName = @"";
                                                       model.showUserId = p.sender;
                                                       model.message = recStr;
                                                       model.time = p.messageTime;
                                                       model.receiver = p.receiver;
                                                       model.showRedHot = YES;
                                                       
                                                       // 从数据库查询红点数量，没有查到就是0
                                                       model.redHotNumber = [self refreshRedHotNum:model];
                                                       NSLog(@"redHotNumber---------->%@",model.redHotNumber);
                                                       
                                                       // 发送通知
                                                       [[NSNotificationCenter defaultCenter] postNotificationName:RefreshMessaegListNotification object:model];
                                                       
                                                       // 给服务器发送ack,确认收到离线消息
                                                       [[ClientSocket shareSocket] doAck:p.messageId];
                                                       
                                                       // 保存消息
                                                       [self saveAcceptedMessage:messageF];
                                                       
                                                       
                                                   }];
        
        
    } else if ([p.mediaType isEqualToString:@"video/mp4"]) {
        
        receiveType = TypeVideo;
        // 保存视频的缩略图
        UIImage *thumbnailImage = [UIImage imageWithData:p.payload];
        UIImage *simpleImage = [UIImage simpleImage:thumbnailImage];
        
        // 视频缩略图地址
        NSString *fileName = [NSString stringWithFormat:@"%@%@",[NSString currentName],@".png"];
        NSString *videoImage =  [[YZMediaManager shareManager] saveVideoImage:thumbnailImage fileName:fileName];
        
        // 原视频的Url
        NSString *orginImagUrlStr = p.mediaLink;
        
        [[YZImageManager shareManager] requestWithUrlStr:orginImagUrlStr
                                               mediaType:p.mediaType
                                                   block:^(NSString *str) {
                                                       fileKey = str;
                                                       YZMessageFrame *messageF = [YZMessageHelper createMessageFrame:receiveType imMessage:p path:fileKey fileKey:videoImage isSender:NO rececivedSenderbySelf:NO senderAvatar:[YZChatPeer shared].receiverAvatar receiverAvatar:[YZUser sharedInstance].avatar];
                                                       
                                                       // 接收Model
                                                       NSString *recStr = @"[视频]";
                                                       YZMessageListModel *model = [YZMessageListModel new];
                                                       model.name = p.sender;
                                                       model.imageName = @"";
                                                       model.showUserId = p.sender;
                                                       model.message = recStr;
                                                       model.time = p.messageTime;
                                                       model.receiver = p.receiver;
                                                       model.showRedHot = YES;
                                                       model.redHotNumber =  @([model.redHotNumber integerValue] + 1);
                                                       // 发送通知
                                                       [[NSNotificationCenter defaultCenter] postNotificationName:RefreshMessaegListNotification object:model];
                                                       
                                                       // 给服务器发送ack,确认收到离线消息
                                                       [[ClientSocket shareSocket] doAck:p.messageId];
                                                       
                                                       // 保存消息
                                                       [self saveAcceptedMessage:messageF];
                                                   }];
        
        
    }
    else if ([p.messageType isEqualToString:@"friend"]) {
        // 接收json
        NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:p.payload options:NSJSONReadingMutableLeaves error:nil];
        if ([[tempDic objectForKey:@"action"] isEqualToString:@"addRequest"]) {
            NSString *reqInfo = tempDic[@"message"] ? : @"";
            
            // 接收Model
            self.lastestModel = [YZFriendModel new];
            self.lastestModel.iconName = @"";
            self.lastestModel.name = @"";
            self.lastestModel.info = reqInfo; // 应该是验证申请的信息
            self.lastestModel.targetId = p.sender;
            self.lastestModel.friendState = NewFriendStateBeAgree;
            self.lastestModel.showRedDot = YES;
            // 同一个人只保留最新的一条
            self.lastestModelArr = [self deDuplication:self.lastestModelArr model:self.lastestModel];
            
            // 发送更新好友列表通知
            NSDictionary *notiInfo = @{@"lastModel":self.lastestModel,@"lastModelArr":self.lastestModelArr};
            [[NSNotificationCenter defaultCenter] postNotificationName:RefreshFriendListNotification object:notiInfo];
            
            // 更新【tab-好友】小红点
            [[NSNotificationCenter defaultCenter] postNotificationName:ShowTabRedDotNotification object:@(1)];
            
            // 给服务器发送ack,确认收到离线消息
            [[ClientSocket shareSocket] doAck:p.messageId];
            
            // 更新是否有新朋友申请的状态
            _haveLatestFriend = YES;
        }
        else if ([[tempDic objectForKey:@"action"] isEqualToString:@"addApproval"]){
            // 刷新好友列表
        }
        
    }
    
}

- (void)saveReceviceAudio:(NSData * _Nonnull)recData {
    // 生成录音文件名
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMddHHmmssSSS"];
    NSString *dateStr = [formatter stringFromDate:date];
    _recorderName = [NSString stringWithFormat:@"%@%@",dateStr,@".aac"];
    _tempRecorderPath = [NSString stringWithFormat:@"%@%@",self.audioRecoderSavePath,_recorderName];
    
    // 写入文件
    NSError *writeErr = nil;
    BOOL wirteRec  = [recData writeToFile:_tempRecorderPath atomically:YES];
    if (!wirteRec) {
        NSLog(@"writeErr--->%@",[writeErr description]);
    }
    NSLog(@"接收到音频文件成功");
}

// 处理接收服务端返回心跳延迟的情况，心跳返回：100000
- (BOOL)isDelayHeartRecData:(NSString *)recStr{
    BOOL isDelay = NO;
    NSUInteger num = 0;
    NSUInteger len = recStr.length;
    num = [YZChatUtils cauculateTimer:recStr subStr:@"100000"];
    if (num > 0) {
        if (num * 6 == len) {
            isDelay = YES;
        }
    }
    
    return isDelay;
}

// 保存接收的消息
- (void)saveAcceptedMessage:(YZMessageFrame *)messageF {
    NSInteger temTimeInterval = [[YZChatUtils getTimeInterval2] integerValue];
    [[YZDBManager sharedManage] insertData:messageF.model.message.playLoad mediaType:messageF.model.message.mediaType sendTime:temTimeInterval filePath:messageF.model.mediaPath fileKey:messageF.model.message.fileKey isSender:NO status:1 table:kChatRecordTable senderAvatar:[YZChatPeer shared].receiverAvatar receiverAvatar:[YZUser sharedInstance].avatar];
}

// 去重
- (NSMutableArray *)deDuplication:(NSMutableArray *)sourceArr
                            model:(YZFriendModel *)friendModel {
    
    NSMutableArray *retArr = [NSMutableArray arrayWithArray:sourceArr];
    if ([sourceArr count] == 0) {
        [retArr addObject:friendModel];
    } else {
        for (YZFriendModel *tempModel in sourceArr) {
            if ([tempModel.targetId isEqualToString:friendModel.targetId]) {
                [retArr removeObject:tempModel];
                // 最新的插到最前面
                [retArr insertObject:friendModel atIndex:0];
                break;
            } else {
                [retArr insertObject:friendModel atIndex:0];
                break;
            }
        }
    }
    
    return retArr;
}

// 更新model小红点数量
- (NSNumber *)refreshRedHotNum:(YZMessageListModel *)model {
    // 从数据库查询红点数量，没有查到就是0
    NSString *condition = [NSString stringWithFormat:@"showUserid = '%@'",model.showUserId];
    NSArray *dotArr = [[YZDBManager sharedManage] queryDataFromTable:kChatMessageListTable andCondition:condition];
    NSNumber *dotNum = @0;
    if ([dotArr count]>0) {
        YZMessageListModel *tempModel = dotArr[0];
        dotNum = tempModel.redHotNumber;
    } else {
        dotNum = @0;
    }
    
    return [NSNumber numberWithInteger:([dotNum intValue] + 1)];;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
